package com.neusoft.hash;

import com.neusoft.hash.entity.Employee;

import java.util.Objects;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 表示HashTable的链表部分
 * @Date 2024-12-28
 */
public class EmployeeLinkedList {

    /**
     * 头指针: 这个链表的head直接指向第一个Employee
     */
    private Employee headEmployee;

    /**
     * 添加雇员: 将该雇员直接加入到链表的最后
     *
     * @param employee 雇员
     */
    public void add(Employee employee) {
        //如果是添加第一个雇员
        if (Objects.isNull(headEmployee)) {
            headEmployee = employee;
            return;
        }
        // 如果不是第一个雇员，则使用一个辅助的指针，帮助定位到最后
        Employee currentEmployee = headEmployee;
        while (Objects.nonNull(currentEmployee.nextEmployee)) {
            // 当没到链表的最后时,链表数据后移
            currentEmployee = currentEmployee.nextEmployee;
        }
        // 退出时直接将emp加入链表
        currentEmployee.nextEmployee = employee;
    }

    /**
     * 遍历制定链表的雇员信息
     *
     * @param no 链表编号
     */
    public void list(int no) {
        if (Objects.isNull(headEmployee)) {
            // 说明当前链表为空
            System.out.println("第 " + (no + 1) + " 号链表为空");
            return;
        }
        System.out.print("第 " + (no + 1) + " 号链表的信息为");
        Employee currentEmployee = headEmployee;
        while (Objects.nonNull(currentEmployee.nextEmployee)) {
            System.out.printf(" => id=%d name=%s\t", currentEmployee.id, currentEmployee.name);
            // 后移，遍历
            currentEmployee = currentEmployee.nextEmployee;
        }
        System.out.println();
    }

    /**
     * 根据id查找雇员
     *
     * @param employeeId 雇员ID
     * @return 雇员
     */
    public Employee findEmployeeById(int employeeId) {
        //判断链表是否为空
        if (Objects.isNull(headEmployee)) {
            System.out.println("链表为空");
            return null;
        }

        Employee currentEmployee = headEmployee;
        while (true) {
            if (currentEmployee.id == employeeId) {
                // 找到直接退出, 这时currentEmployee就指向要查找的雇员
                break;
            }
            if (Objects.isNull(currentEmployee.nextEmployee)) {
                // 说明遍历当前链表没有找到该雇员
                currentEmployee = null;
                break;
            }
            // 链表后移
            currentEmployee = currentEmployee.nextEmployee;
        }

        return currentEmployee;
    }
}
